<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="API," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="任何网络连接都需要经过socket才能连接，HttpURLConnection不需要设置socket，所以，HttpURLConnection并不是底层的连接，而是在底层连接上的一个请求。">
<meta property="og:type" content="article">
<meta property="og:title" content="HttpURLConnection">
<meta property="og:url" content="http://yoursite.com/2017/03/02/201703/HttpURLConnection/index.html">
<meta property="og:site_name" content="HoneyGuide's Blog">
<meta property="og:description" content="任何网络连接都需要经过socket才能连接，HttpURLConnection不需要设置socket，所以，HttpURLConnection并不是底层的连接，而是在底层连接上的一个请求。">
<meta property="og:updated_time" content="2017-03-02T06:35:19.045Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="HttpURLConnection">
<meta name="twitter:description" content="任何网络连接都需要经过socket才能连接，HttpURLConnection不需要设置socket，所以，HttpURLConnection并不是底层的连接，而是在底层连接上的一个请求。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'R1W2VDDO1V',
      apiKey: '773854c4c250e5a5cf9cddd97ebcc167',
      indexName: 'Hexo_search',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/03/02/201703/HttpURLConnection/"/>





  <title> HttpURLConnection | HoneyGuide's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">﻿<div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">HoneyGuide's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay hungry & Stay young</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">

　　　　　　<!--增加的代码 start-->

          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/03/02/201703/HttpURLConnection/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="HoneyGuide">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HoneyGuide's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                HttpURLConnection
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-02T00:00:00+08:00">
                2017-03-02
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>任何网络连接都需要经过socket才能连接，HttpURLConnection不需要设置socket，所以，HttpURLConnection并不是底层的连接，而是在底层连接上的一个请求。<br><a id="more"></a><br>HttpURLConneciton只是一个<strong>抽象类</strong>，自身不能被实例化的原因。HttpURLConnection只能通过URL.openConnection()方法创建具体的实例。</p>
<p>虽然底层的网络连接可以被多个HttpURLConnection实例共享，但每一个HttpURLConnection实例只能发送一个请求。请求结束之后，应该调用HttpURLConnection实例的InputStream或OutputStream的close()方法以释放请求的网络资源，不过这种方式对于持久化连接没用。对于持久化连接，得用disconnect()方法关闭底层连接的socket。</p>
<h3 id="创建HttpURLConnection"><a href="#创建HttpURLConnection" class="headerlink" title="创建HttpURLConnection"></a>创建HttpURLConnection</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">URL url = new URL(&quot;http://localhost:8080/xxx.do&quot;);    </div><div class="line">     </div><div class="line">URLConnection rulConnection = url.openConnection();// 此处的urlConnection对象实际上是根据URL的    </div><div class="line">// 请求协议(此处是http)生成的URLConnection类    </div><div class="line">// 的子类HttpURLConnection,故此处最好将其转化    </div><div class="line">// 为HttpURLConnection类型的对象,以便用到    </div><div class="line">// HttpURLConnection更多的API.如下:    </div><div class="line">     </div><div class="line">HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection;</div></pre></td></tr></table></figure>
<h3 id="设置HttpURLConnection参数"><a href="#设置HttpURLConnection参数" class="headerlink" title="设置HttpURLConnection参数"></a>设置HttpURLConnection参数</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line">// 设定请求的方法为&quot;POST&quot;，默认是GET    </div><div class="line">httpUrlConnection.setRequestMethod(&quot;POST&quot;);    </div><div class="line">    </div><div class="line">// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在    </div><div class="line">// http正文内，因此需要设为true, 默认情况下是false;    </div><div class="line">httpUrlConnection.setDoOutput(true);    </div><div class="line">     </div><div class="line">// 设置是否从httpUrlConnection读入，默认情况下是true;    </div><div class="line">httpUrlConnection.setDoInput(true);    </div><div class="line">     </div><div class="line">// Post 请求不能使用缓存    </div><div class="line">httpUrlConnection.setUseCaches(false);    </div><div class="line">     </div><div class="line">// 设定传送的内容类型是可序列化的java对象    </div><div class="line">// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)    </div><div class="line">httpUrlConnection.setRequestProperty(&quot;Content-type&quot;, &quot;application/x-java-serialized-object&quot;);    </div><div class="line">   </div><div class="line">// 连接，从上述url.openConnection()至此的配置必须要在connect之前完成，    </div><div class="line">httpUrlConnection.connect();</div></pre></td></tr></table></figure>
<h3 id="URLConnection建立连接"><a href="#URLConnection建立连接" class="headerlink" title="URLConnection建立连接"></a>URLConnection建立连接</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">// 此处getOutputStream会隐含的进行connect(即：如同调用上面的connect()方法，    </div><div class="line">// 所以在开发中不调用上述的connect()也可以)。    </div><div class="line">OutputStream outStrm = httpUrlConnection.getOutputStream();    </div><div class="line">// 调用HttpURLConnection连接对象的getInputStream()函数, </div><div class="line">// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。 </div><div class="line">InputStream inStrm = httpConn.getInputStream(); // &lt;===注意，实际发送请求的代码段就在这里 </div><div class="line">// 上边的httpConn.getInputStream()方法已调用,本次HTTP请求已结束,下边向对象输出流的输出已无意义， </div><div class="line">// 既使对象输出流没有调用close()方法，下边的操作也不会向对象输出流写入任何数据. </div><div class="line">// 因此，要重新发送数据时需要重新创建连接、重新设参数、重新创建流对象、重新写数据、 </div><div class="line">// 重新发送数据(至于是否不用重新这些操作需要再研究) </div><div class="line">objOutputStm.writeObject(new String(&quot;&quot;)); </div><div class="line">httpConn.getInputStream()</div></pre></td></tr></table></figure>
<h3 id="HttpURLConnection发送请求"><a href="#HttpURLConnection发送请求" class="headerlink" title="HttpURLConnection发送请求"></a>HttpURLConnection发送请求</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">// 现在通过输出流对象构建对象输出流对象，以实现输出可序列化的对象。    </div><div class="line">ObjectOutputStream objOutputStrm = new ObjectOutputStream(outStrm);    </div><div class="line">     </div><div class="line">// 向对象输出流写出数据，这些数据将存到内存缓冲区中    </div><div class="line">objOutputStrm.writeObject(new String(&quot;我是测试数据&quot;));    </div><div class="line">     </div><div class="line">// 刷新对象输出流，将任何字节都写入潜在的流中（些处为ObjectOutputStream）    </div><div class="line">objOutputStm.flush();    </div><div class="line">    </div><div class="line">// 关闭流对象。此时，不能再向对象输出流写入任何数据，先前写入的数据存在于内存缓冲区中,    </div><div class="line">// 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器    </div><div class="line">objOutputStm.close();</div></pre></td></tr></table></figure>
<h3 id="HttpURLConneciton获取响应"><a href="#HttpURLConneciton获取响应" class="headerlink" title="HttpURLConneciton获取响应"></a>HttpURLConneciton获取响应</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"> // 调用HttpURLConnection连接对象的getInputStream()函数,  </div><div class="line">InputStream inStrm = httpConn.getInputStream();</div></pre></td></tr></table></figure>
<h3 id="设置POST参数"><a href="#设置POST参数" class="headerlink" title="设置POST参数"></a>设置POST参数</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">OutputStream os = httpConn.getOutputStream();    </div><div class="line">             String param = new String();    </div><div class="line">             param = &quot;CorpID=&quot; + CorpID +    </div><div class="line">                     &quot;&amp;LoginName=&quot; + LoginName+    </div><div class="line">                     &quot;&amp;send_no=&quot; + phoneNumber +    </div><div class="line">                     &quot;&amp;msg=&quot; + java.net.URLEncoder.encode(msg,&quot;GBK&quot;); ;    </div><div class="line">             os.write(param.getBytes());</div></pre></td></tr></table></figure>
<h3 id="超时设置"><a href="#超时设置" class="headerlink" title="超时设置"></a>超时设置</h3><p>防止网络异常的情况下，可能会导致程序僵死而不继续往下执行。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">System.setProperty(&quot;sun.net.client.defaultConnectTimeout&quot;, &quot;30000&quot;);  //连接主机的超时时间（单位：毫秒）</div><div class="line">System.setProperty(&quot;sun.net.client.defaultReadTimeout&quot;, &quot;30000&quot;);  //从主机读取数据的超时时间（单位：毫秒）</div></pre></td></tr></table></figure></p>
<h3 id="注意事项"><a href="#注意事项" class="headerlink" title="注意事项"></a>注意事项</h3><ul>
<li>HttpURLConnection的connect()函数，实际上只是建立了一个与服务器的tcp连接，并没有实际发送http请求。无论是post还是get，http请求实际上直到HttpURLConnection的getInputStream()这个函数里面才正式发送出去。 </li>
<li>在用POST方式发送URL请求时，URL请求参数的设定顺序是重中之重，对connection对象的一切配置（那一堆set函数）都必须要在connect()函数执行之前完成。而对outputStream的写操作，又必须要在inputStream的读操作之前。这些顺序实际上是由http请求的格式决定的。如果inputStream读操作在outputStream的写操作之前，会抛出异常。</li>
<li>http请求实际上由两部分组成，一个是<strong>http头</strong>，所有关于此次http请求的配置都在http头里面定义，一个是<strong>正文content</strong>。connect()函数会根据HttpURLConnection对象的配置值生成http头部信息，因此在调用connect函数之前。就必须把所有的配置准备好。</li>
<li>在http头后面紧跟着的是http请求的正文，正文的内容是通过outputStream流写入的，实际上outputStream不是一个网络流，充其量是个字符串流，往里面写入的东西不会立即发送到网络，而是存在于内存缓冲区中，待outputStream流关闭时，根据输入的内容生成http正文。</li>
<li>至此，http请求的东西已经全部准备就绪。在getInputStream()函数调用的时候，就会把准备好的http请求正式发送到服务器了，然后返回一个输入流，用于读取服务器对于此次http请求的返回信息。由于http请求在getInputStream的时候已经发送出去了（包括http头和正文），因此在getInputStream()函数之后对connection对象进行设置（对http头的信息进行修改）或者写入outputStream（对正文进行修改）都是没有意义的了，执行这些操作会导致异常的发生。 </li>
</ul>
<h3 id="GET和POST的区别"><a href="#GET和POST的区别" class="headerlink" title="GET和POST的区别"></a>GET和POST的区别</h3><p>Get是向服务器发索取数据的一种请求，而Post是向服务器提交数据的一种请求，在FORM（表单）中，Method默认为”GET”，实质上，GET和POST只是发送机制不同。</p>
<ul>
<li>GET请求的数据会附在URL之后（就是把数据放置在HTTP协议头中），以?分割URL和传输数据，参数之间以&amp;相连，如：login.action?name=hyddd&amp;password=idontknow&amp;verify=%E4%BD%A0%E5%A5%BD。而POST把提交的数据则放置在是HTTP包的包体中。</li>
<li>GET请求的数据通常较少，而POST请求的数据没有大小限制。</li>
<li>POST的安全性要比GET的安全性高。比如：通过GET提交数据，用户名和密码将明文出现在URL上，因为(1)登录页面有可能被浏览器缓存，(2)其他人查看浏览器的历史纪录，那么别人就可以拿到你的账号和密码了。</li>
</ul>
<h3 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h3><p><a href="http://blog.csdn.net/woxueliuyun/article/details/43267365" target="_blank" rel="external">http://blog.csdn.net/woxueliuyun/article/details/43267365</a><br><a href="http://blog.csdn.net/x1617044578/article/details/8668632" target="_blank" rel="external">http://blog.csdn.net/x1617044578/article/details/8668632</a><br><a href="http://www.cnblogs.com/hyddd/archive/2009/03/31/1426026.html" target="_blank" rel="external">http://www.cnblogs.com/hyddd/archive/2009/03/31/1426026.html</a> </p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/API/" rel="tag"># API</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/03/01/201703/Activity和Service交互/" rel="next" title="Activity和Service交互">
                <i class="fa fa-chevron-left"></i> Activity和Service交互
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/02/201703/SharedPreferneces/" rel="prev" title="SharedPreferneces">
                SharedPreferneces <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="HoneyGuide" />
          <p class="site-author-name" itemprop="name">HoneyGuide</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              
                <span class="site-state-item-count">34</span>
                <span class="site-state-item-name">标签</span>
              
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建HttpURLConnection"><span class="nav-number">1.</span> <span class="nav-text">创建HttpURLConnection</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#设置HttpURLConnection参数"><span class="nav-number">2.</span> <span class="nav-text">设置HttpURLConnection参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#URLConnection建立连接"><span class="nav-number">3.</span> <span class="nav-text">URLConnection建立连接</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#HttpURLConnection发送请求"><span class="nav-number">4.</span> <span class="nav-text">HttpURLConnection发送请求</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#HttpURLConneciton获取响应"><span class="nav-number">5.</span> <span class="nav-text">HttpURLConneciton获取响应</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#设置POST参数"><span class="nav-number">6.</span> <span class="nav-text">设置POST参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#超时设置"><span class="nav-number">7.</span> <span class="nav-text">超时设置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注意事项"><span class="nav-number">8.</span> <span class="nav-text">注意事项</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#GET和POST的区别"><span class="nav-number">9.</span> <span class="nav-text">GET和POST的区别</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参考"><span class="nav-number">10.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HoneyGuide</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  



  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="local-search-pop-overlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


  

</body>
</html>
